package controllers.bluehat;

import java.util.HashMap;
import java.util.List;

import org.hibernate.ejb.criteria.expression.function.CurrentDateFunction;

import play.data.validation.Valid;
import play.i18n.Messages;
import utils.json.data.MessageJson;
import models.Focus;
import models.IdeaRequest;
import models.InformationRequest;
import models.User;

public class InformationRequestController extends BlueHatBaseController {
	
	/**
	 * Renders the form to create new information request about the current focus.
	 */
	public static void form(Long id) {
		Focus focus = Focus.getById(id, Focus.findByOwner(getCurrentUser()));
		if(focus == null) error(); // TODO same code that in FocusController
		
		render(focus);
	}
	
	public static void save(Long id, InformationRequest infoRequest) {
		Focus focus = Focus.getById(id, Focus.findByOwner(getCurrentUser()));
		if(!getCurrentUser().equals(focus.owner)) error(); // TODO same code that in FocusController
		infoRequest.focus = focus;
		
		// Validations TODO add more validations based on dates.
		// Custom validation. Restriction over the dates.
		List<InformationRequest> open = InformationRequest.findAllOpen(infoRequest.start, focus.informationRequest);
		if(open.size() > 0) {
			validation.addError("Dates", "Ya hay procesos planificados en esa fecha. Verifique que es correcta la seleccion de fechas", new String[]{});
		}
		validation.valid(infoRequest);
		if(validation.hasErrors()) {
			params.flash(); // add http parameters to the flash scope
			validation.keep(); // keep the errors for the next request
			render("bluehat/informationRequestController/form.html", focus, infoRequest);
		} else {
			infoRequest.save();
		}
		
		FocusController.detail(id);
	}
	
	public static void detail(Long id) {
		InformationRequest infoRequest = InformationRequest.getById(id, null);
		
		render(infoRequest);
	}
	
	public static void confirm_delete(Long id) {
		InformationRequest infoRequest = InformationRequest.getById(id, null); 
		render(infoRequest);
	}
	
	public static void delete(Long id, Boolean confirm) {
		InformationRequest infoRequest = InformationRequest.getById(id, null); 
		Long focusId = infoRequest.focus.id;
		// TODO validation!
		if(confirm != null && confirm) {
			/*Logger.info("Removing a focus! This action will remove all child relations. This action is executed here!");
			for(InformationRequest infoRequest : focus.informationRequest.iter()) {
				Logger.debug("Now removing information units!");
				infoRequest.informations.delete();
			}
			Logger.debug("Now removing all information requests!");
			focus.informationRequest.delete();*/
			infoRequest.delete();
		}
		
		FocusController.detail(focusId);
	}
}
